package com.fengmi.goods.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengmi.api.search.SearchApi;
import com.fengmi.goods.*;
import com.fengmi.goods.mapper.MallGoodsBrandMapper;
import com.fengmi.goods.mapper.MallGoodsCatMapper;
import com.fengmi.goods.mapper.MallGoodsMapper;
import com.fengmi.goods.mapper.MallGoodsSkuMapper;
import com.fengmi.goods.service.IMallGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengmi.vo.CatHotGoodsVO;
import com.fengmi.vo.ResultVO;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuxm
 * @since 2021-10-14
 */
@Service
public class MallGoodsServiceImpl extends ServiceImpl<MallGoodsMapper, MallGoods> implements IMallGoodsService {
    @Autowired
    private SearchApi searchApi;

    @Autowired
    private MallGoodsBrandMapper goodsBrandMapper;
    @Autowired
    private MallGoodsCatMapper catMapper;
    @Autowired
    private RocketMQTemplate template;
    @Autowired
    private MallGoodsSkuMapper mallGoodsSkuMapper;

    @Override
    public List<CatHotGoodsVO> findCatAndGoodsListTopn(Integer topn) {
        //获取商品分类列表
        List<MallGoodsCat> catHasGoods = this.baseMapper.findCatHasGoods();
       List<CatHotGoodsVO> list= catHasGoods.stream().map(cat->{
            CatHotGoodsVO catHotGoodsVO=new CatHotGoodsVO();
            catHotGoodsVO.setCat(cat);
            //根据分类id获取列表
            List<MallGoods> goodsByCatId = this.baseMapper.findGoodsByCatId(cat.getId() + "", topn);
            catHotGoodsVO.setGoodsList(goodsByCatId);
            return catHotGoodsVO;

        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<MallGoods> findGoodsSpuInfo() {
        return this.baseMapper.findGoodsSpuInfo();
    }

    @Override
    public ResultVO audit(String spuId) {
        MallGoods mallGoods = this.baseMapper.selectById(spuId);
        if(mallGoods ==null){
            return new ResultVO(false,"商品不存在");
        }
        //查询品牌信息
        MallGoodsBrand mallGoodsBrand = goodsBrandMapper.selectById(mallGoods.getBrandId());
        mallGoods.setBrand(mallGoodsBrand);
        //查询商品的分类信息
        MallGoodsCat mallGoodsCat = catMapper.selectById(mallGoods.getCategory3Id());
        mallGoods.setCat3(mallGoodsCat);
        MallGoodsCat mallGoodsCat1 = catMapper.selectById(mallGoods.getCategory1Id());
        mallGoods.setCat1(mallGoodsCat1);
        MallGoodsCat mallGoodsCat2 = catMapper.selectById(mallGoods.getCategory2Id());
        mallGoods.setCat2(mallGoodsCat2);

        mallGoods.setAuditStatus("1");
        this.baseMapper.updateById(mallGoods);

//        //远程调用搜索服务实现同步索引库
//        try {
//            searchApi.goodsToes(mallGoods);
//        } catch (Exception e) {
//            e.printStackTrace();
//            mallGoods.setAuditStatus("0");
//            this.baseMapper.updateById(mallGoods);
//        }


//        发送消息（不能发送单向消息）
        SendResult result = template.syncSend("goodsToElasticsearch:goods", mallGoods);


        if (result.getSendStatus()!= SendStatus.SEND_OK){
            //回退
            mallGoods.setAuditStatus("0");
            this.baseMapper.updateById(mallGoods);
            return  new ResultVO(false,"审核失败:同步索引库失败");

        }
        //发送消息（生成静态化页面）
        SendResult resulthtml = template.syncSend("goodsToHTML:goods", mallGoods.getSpuId());
        if (resulthtml.getSendStatus()!= SendStatus.SEND_OK){
            //回退
            mallGoods.setAuditStatus("0");
            this.baseMapper.updateById(mallGoods);
            return  new ResultVO(false,"审核失败：网页静态化失败");

        }
        return new ResultVO(true,"审核成功");




//       final  boolean[] sendRes={false};
//            template.asyncSend("goodsToElasticsearch:goods", mallGoods, new SendCallback() {
//                @Override
//                public void onSuccess(SendResult sendResult) {
//                    sendRes[0]=true;
//                }
//
//                @Override
//                public void onException(Throwable throwable) {
//
//                }
//            });
    }

    @Override
    public MallGoods findGoodsDetail(String spuId) {
        MallGoods mallGoods = this.baseMapper.selectById(spuId);
        //获取sku列表
        QueryWrapper<MallGoodsSku> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("is_default");
        queryWrapper.eq("spu_id",spuId);
        List<MallGoodsSku> mallGoodsSkus = mallGoodsSkuMapper.selectList(queryWrapper);
        mallGoods.setSkuList(mallGoodsSkus);
        List<SpecAndOpts> specAndOpts = JSONUtil.toList(mallGoods.getSpuSpecInfo(), SpecAndOpts.class);
        mallGoods.setSpecAndOpts(specAndOpts);
        return mallGoods;
    }
}
